package com.le.tester.book.effectivejava3rdchinese.secondReading.l30;

import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.UnaryOperator;

/**
 * createTime：2024-09-09 11:17
 * description：方法参数泛型化,使用泛型最大的优点就是参数可以不用强制转换
 */
public class Union {

    private static UnaryOperator<Object> IDENTITY_FN = (t) -> t;

    //普通方式
//    public static Set union(Set s1, Set s2) {
//        Set result = new HashSet(s1);
//        result.addAll(s2);
//        return result;
//    }
    //泛型方式
    public static <E> Set<E> union(Set<? extends E> s1, Set<? extends E> s2) {
        Set<E> result = new HashSet<>(s1);
        result.addAll(s2);
        return result;
    }


    public static <T> UnaryOperator<T> identityFunction() {
        return (UnaryOperator) IDENTITY_FN;
    }

    public static <E extends Comparable<E>> E max(Collection<E> c) {
        if (c.isEmpty()) {
            throw new IllegalArgumentException("Empty collection");
        }
        E result = null;

        for (E e : c) {
            if (result == null || e.compareTo(result) > 0) {
                result = Objects.requireNonNull(e);
            }
        }
        return result;
    }

//    public void pushAll(Iterable<E> src) {
//        for (E e : src) {
//            pus
//        }
//    }


    public static void main(String[] args) {
        String[] strings = {"jute", "hemp", "nylon"};
        UnaryOperator<String> sameString = identityFunction();

        for (String s : strings) {
            System.out.println(sameString.apply(s));
        }

        Number[] numbers = {1, 2.0, 3L};
        UnaryOperator<Number> sameNumber = identityFunction();

        for (Number number : numbers) {
            System.out.println(sameNumber.apply(number));
        }


    }

}
